import { useLazyQuery, useQuery } from "@apollo/client"
import { useParams } from "react-router"
import { usePath } from "../../../../hooks/usePath"
import { QueryTestByIdQuery, QueryTestChapterQuery, QueryTestChapterResult } from "../../../admin/test/group/chapter/page"
import { QueryTestGroupByIdResult, QueryTestGroupByIdQuery } from "../../../admin/test/group/page"
import ChapterInfo from "./ChapterInfo"
import { useEffect, useState } from "react"
import { classNames } from "primereact/utils"
import { QueryTestChapterByIdQuery } from "../../../admin/test/group/chapter/paper/page"
import PaperList from "./PaperList"


const TestGroupChapterPage = () => {
  const params = useParams()
  const groupId = parseInt(params.groupId || "0")
  const testId = parseInt(params.testId || "0")
  const group = useQuery<QueryTestGroupByIdResult>(QueryTestGroupByIdQuery, {
    variables: {
      id: groupId
    }
  })
  const test = useQuery<QueryTestByIdQuery>(QueryTestByIdQuery, {
    variables: {
      id: testId
    }
  })
  const { data } = useQuery<QueryTestChapterResult>(QueryTestChapterQuery, {
    variables: {
      id: testId
    }
  })
  const dataSource = [...(data?.queryTestChapters || [])]
  usePath([{ title: "模拟测试", href: "/test" }, { href: `/test/${groupId}/group`, title: group.data?.queryTestGroupById.name || "" }, { title: test.data?.queryTestById.name || "" }])
  const [current, setCurrent] = useState(-1);
  const [getChapter, chapter] = useLazyQuery(QueryTestChapterByIdQuery)
  useEffect(() => {
    if (current !== -1) return;
    if (!dataSource.length) return;
    setCurrent(dataSource[0].id)
  }, [dataSource, current])
  useEffect(() => {
    if (current === -1) return;
    getChapter({
      variables: {
        id: current,
        papers: true
      },
      fetchPolicy: "no-cache"
    })
  }, [current])
  return (
    <div>
      <ChapterInfo
        group={group.data?.queryTestGroupById}
        chapter={chapter.data?.queryTestChapterById}
        test={test.data?.queryTestById}
      />
      {dataSource.length > 1 && <div className="bg-blue-400 flex">
        {dataSource.sort((a, b) => a.order - b.order).map((item) => {
          return (
            <div
              key={item.id}
              className={classNames(
                "text-center cursor-pointer",
                current === item.id && "bg-blue-500"
              )}
              onClick={() => {
                setCurrent(item.id)
              }}
              style={{
                width: `${100 / dataSource.length}%`,
              }}
            >
              {item.name}
            </div>
          )
        })}
      </div>}
      {!!chapter.data?.queryTestChapterById && <PaperList
        test={test.data?.queryTestById}
        chapter={chapter.data?.queryTestChapterById}
        baseHref={`/test/${groupId}/group/${testId}/chapter/${current}/paper`}
      />}
    </div>
  )
}
export default TestGroupChapterPage